//
//  ResetPasswordViewController.m
//  有材网
//
//  Created by 肖扬 on 16/1/25.
//  Copyright © 2016年 肖扬. All rights reserved.
//

#import "ResetPasswordViewController.h"

@interface ResetPasswordViewController (){
    NSTimer *_timer;
    int timecount;
    UIButton *hqBtn;
    BOOL _isTime;
    NSDate *saveDate;
}

@end

@implementation ResetPasswordViewController
@synthesize tel,accTextField,pwdTextField,codeTextField;
-(void)verificationTime{
    int time = [saveDate timeIntervalSinceNow];
    
    if (time<0)
    {
        NSString *str = [NSString stringWithFormat:@"重新发送"];
        [hqBtn setEnabled:YES];
        [hqBtn setTitle:str forState:0];
    }
    else
    {
        NSString *str = [NSString stringWithFormat:@"%ds",time];
        [hqBtn setEnabled:NO];
        [hqBtn setTitle:str forState:0];
    }
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(verificationTime) userInfo:nil repeats:NO];
}
#pragma mark -- 获取验证码
-(void)getSms_code{
    TIME
    HEADDIC(nowTime, SMS_CODE);
    NSString *mobile = self.accTextField.text;
    NSDictionary *body = @{
                           @"mode":@"3",
                           @"mobile":mobile,
                           };
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSLog(@"result___%@",result);
    NSMutableDictionary *json = [result objectFromJSONString];
    if (json!=nil) {
        if ([[json objectForKey:@"err_code"] integerValue]==0) {
            saveDate = [NSDate dateWithTimeIntervalSinceNow:60];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(verificationTime) userInfo:nil repeats:NO];
        }else{
            SHOW_TITLEALERT(@"提示", @"验证码发送失败");
        }
    }
}
-(void)modifypassword{
    TIME
    HEADDIC(nowTime, MEMBERPASSWORD);
    NSString *mobile = self.accTextField.text;
    if ([self.accTextField.text rangeOfString:@"**"].location != NSNotFound) {
        mobile = [[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"];
    }
    NSDictionary *body = @{
                           @"mobile":mobile,
                           @"sms_code":self.codeTextField.text,
                           @"password":self.pwdTextField.text
                           };
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSMutableDictionary *json = [result objectFromJSONString];
    if ([[json objectForKey:@"err_code"] integerValue]==0) {
        [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"userPwd"];
        [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"newpassword"];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"密码重置成功，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 255;
        [alert show];
    }else{
        SHOW_ALERT([json objectForKey:@"err_message"]);
    }
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 255) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(void)hqBtnClick{
    if (self.accTextField.text.length !=11) {
        SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
        return;
    }
    if (![Unity isValidateTelphone:self.accTextField.text]) {
        SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
        return;
    }
    [self getSms_code];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setView];
    [ [NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:nil];
    // Do any additional setup after loading the view.
}
-(void)textChange
{
    UIButton *loginBtn = (UIButton *)[self.view viewWithTag:12];
    if (self.accTextField.text.length !=0 && self.pwdTextField.text.length !=0 && self.codeTextField.text.length !=0) {
        if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
            if (![Unity isValidateTelphone:self.accTextField.text]) {
                [loginBtn setEnabled:NO];
                return;
            }
        }
        if (![Unity isMsgCode:self.codeTextField.text]) {
            [loginBtn setEnabled:NO];
            return;
        }
        [loginBtn setEnabled:YES];
    }else{
        [loginBtn setEnabled:NO];
    }
}
-(void)setView{
    UIView *navView = [self createViewFrame:CGRectMake(0, 0, SWIDTH, 64) bgColor:UIColorFromRGB(0x247ac4) tag:0];
    [self.view addSubview:navView];
    [self.leftBtn setHidden:NO];
    [self.leftBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.leftBtn];
    [self.titleLab setText:self.title];
    [self.titleLab setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:self.titleLab];
    
    UIButton *btn1 = [UIButton buttonWithType:0];
    btn1.frame = CGRectMake(20, 20, 40, 44);
    [btn1 setBackgroundColor:[UIColor clearColor]];
    [btn1 addTarget:self action: @selector(backClick:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
    UIView *tempView = [self createViewFrame:CGRectMake(10, 77, SWIDTH - 20, 127) bgColor:UIColorFromRGB(0xffffff) tag:0];
    tempView.layer.masksToBounds = YES;
    tempView.layer.cornerRadius = 6.0;
    tempView.layer.borderWidth = 0.6;
    tempView.layer.borderColor = [[UIColor whiteColor] CGColor];
    [self.view addSubview:tempView];
    
    UIView *lineView = [self createViewFrame:CGRectMake(0, 42, SWIDTH-20, 0.5) bgColor:[UIColor grayColor] tag:0];
    lineView.alpha = 0.2;
    [tempView addSubview:lineView];
    
    UIImageView *img1 = [self createImageViewFrame:CGRectMake(15, 11, 13, 20) image:nil imageName:@"登录-手机icon" tag:0];
    [tempView addSubview:img1];
    
    UIImageView *img2 = [self createImageViewFrame:CGRectMake(15, 97, 13, 20) image:nil imageName:@"登录密码" tag:0];
    [tempView addSubview:img2];
    
    
    UIImageView *img3 = [self createImageViewFrame:CGRectMake(15, 54, 13, 20) image:nil imageName:@"验证码" tag:0];
    [tempView addSubview:img3];
    
    UIView *lineView1 = [self createViewFrame:CGRectMake(0, 85, SWIDTH-20, 0.5) bgColor:[UIColor grayColor] tag:0];
    lineView1.alpha = 0.2;
    [tempView addSubview:lineView1];
    
    self.accTextField = [self createTextFieldFrame:CGRectMake(36, 0, SWIDTH - 160, 42) bgColor:[UIColor clearColor] tag:10 keyBoardType:0];
    self.accTextField.textAlignment = NSTextAlignmentLeft;
    self.accTextField.delegate = self;
    self.accTextField.placeholder = @"手机号";
//    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"]isEqualToString:@""]) {
//        self.accTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"];
//    }
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"]isEqualToString:@""]||[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"]!=nil) {
        NSString *telPhone= [[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"] stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        NSLog(@"tel:%@",telPhone);
        self.accTextField.text = telPhone;
    }
    self.accTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.accTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.accTextField.font = FONT14;
    [tempView addSubview:self.accTextField];
    
    UIView *line1 = [self createViewFrame:CGRectMake(SWIDTH - 40 - 85, 11, 0.5, 20) bgColor:UIColorFromRGB(0xe8e8e8) tag:0];
    //    line1.alpha = 0.2;
    [tempView addSubview:line1];
    
    hqBtn = [UIButton buttonWithType:0];
    hqBtn.frame = CGRectMake(SWIDTH - 122, 9, 80, 24);
    [hqBtn setTitle:@"获取验证码" forState:0];
    //    hqBtn.titleLabel.textColor = UIColorFromRGB(0x247ac4);
    hqBtn.backgroundColor = [UIColor clearColor];
    [hqBtn setTitleColor:UIColorFromRGB(0x247ac4) forState:0];
    [tempView addSubview:hqBtn];
    hqBtn.clipsToBounds = YES;
    hqBtn.layer.cornerRadius = 5.0f;
    [hqBtn addTarget:self action:@selector(hqBtnClick) forControlEvents:7];
    hqBtn.titleLabel.font = FONT14;
    
    self.codeTextField = [self createTextFieldFrame:CGRectMake(36, 43, SWIDTH - 53, 42) bgColor:[UIColor clearColor] tag:18 keyBoardType:0];
    self.codeTextField.textAlignment = NSTextAlignmentLeft;
    self.codeTextField.delegate = self;
    self.codeTextField.placeholder = @"验证码";
    self.codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.codeTextField.font = FONT14;
    [tempView addSubview:self.codeTextField];
    
    self.pwdTextField = [self createTextFieldFrame:CGRectMake(36, 85, SWIDTH - 53, 42) bgColor:[UIColor clearColor] tag:11 keyBoardType:0];
    self.pwdTextField.textAlignment = NSTextAlignmentLeft;
    self.pwdTextField.delegate = self;
    self.pwdTextField.secureTextEntry = YES;
    self.pwdTextField.placeholder = @"新密码";
    self.pwdTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.pwdTextField.font = FONT14;
    [tempView addSubview:self.pwdTextField];
    
    UIButton *loginBtn = [self createButtonFrame:CGRectMake(10, 219, SWIDTH - 20, 43) title:@"提交" viewController:self selector:@selector(submit:) tag:12];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"登录-点击后按钮"] forState:UIControlStateNormal];
    [loginBtn setEnabled:NO];
    loginBtn.titleLabel.font = FONT14;
    [self.view addSubview:loginBtn];
    
    if (self.accTextField.text.length !=0) {
        [self.codeTextField becomeFirstResponder];
    }else{
        [self.accTextField becomeFirstResponder];
    }
    
}
-(void)submit:(UIButton *)sender{
    //TODO:修改密码
    if (self.accTextField.text.length!=11) {
        SHOW_ALERT(@"请填写手机号");
    }
    if (self.codeTextField.text.length ==0) {
        SHOW_ALERT(@"请输入验证码");
    }
    if (self.pwdTextField.text.length == 0) {
        SHOW_ALERT(@"请输入新密码");
    }
    if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
        if (![Unity isValidateTelphone:self.accTextField.text]) {
            SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
            return;
        }
    }
    if (![Unity isMsgCode:self.codeTextField.text]) {
        SHOW_TITLEALERT(@"提示", @"验证码有误");
        return;
    }
    [self modifypassword];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.accTextField) {
        if ([string isEqualToString:@""]) {
            NSString *acc = self.accTextField.text;
            if ([acc rangeOfString:@"**"].location != NSNotFound) {
                self.accTextField.text = @"";
            }
        }
    }
    return YES;
}
-(void)backClick:(UIButton *)sender{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
 UIButton *loginBtn = (UIButton *)[self.view viewWithTag:12];
 if (textField == self.accTextField) {
 NSString *checkString;
 if (range.location == 11) {
 [loginBtn setEnabled:YES];
 return NO;
 }else{
 if (![string isEqualToString:@""]) {
 if (self.pwdTextField.text.length !=0 && self.codeTextField.text.length !=0) {
 if (range.location == 10) {
 [loginBtn setEnabled:YES];
 }else{
 [loginBtn setEnabled:NO];
 }
 }
 checkString=[self.accTextField.text stringByAppendingString:string];
 }else{
 checkString=[checkString stringByDeletingLastPathComponent];
 [loginBtn setEnabled:NO];
 }
 return YES;
 }
 }
 
 if (textField == self.pwdTextField) {
 if (![string isEqualToString:@""]) {
 if (self.accTextField.text.length == 11 && self.codeTextField.text.length !=0) {
 [loginBtn setEnabled:YES];
 }else{
 [loginBtn setEnabled:NO];
 }
 }else{
 [loginBtn setEnabled:NO];
 }
 }
 
 if (textField == self.codeTextField) {
 if (![string isEqualToString:@""]) {
 if (self.accTextField.text.length == 11 && self.pwdTextField.text.length !=0) {
 [loginBtn setEnabled:YES];
 }else{
 [loginBtn setEnabled:NO];
 }
 }else{
 [loginBtn setEnabled:NO];
 }
 }
 
 return YES;
 }

*/

@end
